<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      :btn-list="fullInfo.btnList"
    >
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t("basic_information") }}</p>
        </div>
        <div class="model-panel-body">
          <PageForm
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            v-model:data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
            @handleEvent="formHandleEvent"
          >
            <template v-slot:form-supplierName>
              <el-input
                v-model="formInfo.data.supplierName"
                class="not-mongolia"
                type="input"
                placeholder="请选择供应商"
                :disabled="true"
              >
                <template #append>
                  <el-icon @click="selectSupplier"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
          </PageForm>
        </div>
      </div>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t("detailInfo") }}</p>
        </div>
        <div class="model-panel-body">
          <PageFilter
            v-model:query="filterInfo.query"
            :filter-list="filterInfo.list"
          >
            <template v-slot:filter-addProduct>
              <el-button
                :disabled="!formInfo.data.supplierName"
                @click="addProduct"
                >添加发票</el-button
              >
            </template>
            <template v-slot:filter-removeProduct>
              <el-button
                :disabled="!tableInfo.selections.length"
                @click="removeProduct"
                >删除发票</el-button
              >
            </template>
          </PageFilter>
          <div>
            <el-form ref="tableForm" :model="tableInfo" style="width: 100%">
              <PageTable
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :tab-index="false"
                :check-box="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :merge-data="tableInfo.mergeData"
                :merge-filed="tableInfo.mergeFiled"
                :isRowClickSelect="true"
                :isDynamic="true"
                @handleEvent="handleEvent"
              >
                <template v-slot:col-discountsAmount="scope">
                  <el-form-item
                    v-if="scope.$index >= 0"
                    @click.stop=""
                    :prop="`data.${scope.$index}.discountsAmount`"
                    :rules="
                      scope.$index >= 0
                        ? [
                            {
                              required: scope.$index >= 0,
                              message: '请输入优惠金额',
                              trigger: 'blur',
                            },
                          ]
                        : []
                    "
                  >
                    <el-input-number
                      v-model.lazy="scope.row.discountsAmount"
                      clearable
                      controls-position="right"
                      :precision="
                        $store.state.permission.systemConfig.price_precision
                      "
                      @change="changeNum($event, scope.row, `discountsAmount`, scope.row.shouldPayAmount)"
                      :min="0"
                      :max="9999999"
                    />
                  </el-form-item>
                </template>

              </PageTable>
            </el-form>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <AddProduct
      v-if="productInfo.visible"
      v-model:query="productInfo.query"
      :api="productInfo.api"
      v-model:show-dialog="productInfo.visible"
      @callback="selectProduct"
    />
    <!-- 选择供应商 -->
    <SelectSupplier
      v-if="supplierInfo.visible"
      @callback="callBackSupplier"
      v-model:showDialog="supplierInfo.visible"
      v-model:query="supplierInfo.query"
      :checkBox="false"
      :highlightRow="true"
    />
  </div>
</template>
<script setup name="meetManageModify">
import {
  shouldPayOrderDetailAll,
  getShouldPayOrderDetails,
  shouldPayOrderUpdate,
  shouldPayOrderSubmit,
} from "@/api/receipt.js";
import AddProduct from "./addProduct";
const { proxy } = getCurrentInstance();
const props = defineProps(["visible", "orderId", "title",'data']);

const fullInfo = ref({
  btnList: [{ label: "保存", event: save, show: true }],
});
const formRefs = ref(undefined);
const formInfo = ref({
  ref: null,
  data: {
    supplierName:'',
    supplierId:'',
    use:'',
    checkNumber:'',
    remark:'',
  },
  fieldList: [
    { label: "供应商", value: "supplierName", type: "slot" },
    {
      label: "用途",
      value: "use",
      type: "input",
    },
    {
      label: "支票号",
      value: "checkNumber",
      type: "input",
    },
    {
      label: "科目",
      value: "account",
      type: "input",
    },
    {
      label: "备注",
      value: "remark",
      type: "textarea",
    },
  ],
  rules: {
    // use: [
    //   {
    //     required: true,
    //     message: "请输入用途",
    //     trigger: "blur",
    //   },
    // ],
    supplierName: [
      {
        required: true,
        message: "请选择供应商",
        trigger: "blur",
      },
    ],
  },
  labelWidth: "120px",
});
// 过滤相关配置
const filterInfo = ref({
  query: {
    receiptNumber: "",
  },
  list: [
    {
      type: "slot",
      label: "添加发票",
      value: "addProduct",
    },
    {
      type: "slot",
      label: "删除发票",
      value: "removeProduct",
    },
  ],
});
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  summaryFieldList: [
    { value: 'shouldPayAmount', formatter: proxy.$fn.qtyFormatter },
    { value: 'discountsAmount', formatter: proxy.$fn.TripartiteMethod },
    { value: 'payAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  mergeData: {},
  mergeFiled: ["payAmount"],
  fieldList: [
    {
      label: "发票号",
      value: "receiptNumber",
    },
    {
      label: "应付金额",
      value: "shouldPayAmount",
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: "优惠金额",
      value: "discountsAmount",
      type: "slot",
      width: 148,
    },
    {
      label: "付款金额",
      value: "payAmount",
      formatter: proxy.$fn.TripartiteMethod,
    },
  ],
  handle: {
    fixed: "right",
    label: "操作",
    width: "120",
    btList: [
      {
        label: "删除发票",
        event: removeProduct,
        popconfirmText: "删除后将改变数据,是否继续？",
        show: true,
      },
    ],
  },
});
const productInfo = ref({
  visible: false,
  query: {
  },
});
const supplierInfo = ref({
  visible: false,
  query: {
    supplierAuth: "supplierId",
  },
});
const showDialog = computed({
  get() {
    return props.visible;
  },
  set(val) {
    proxy.$emit("update:visible", val); // 更新父组件visible
  },
});

onMounted(() => {
  if (props.orderId) {
    getMain();
    formInfo.value.data.id = props.orderId
  }
  formRefs.value = [proxy.$refs["tableForm"], formInfo.value.ref];
});

function formHandleEvent(event) {
  if (event === "changeSettleType") {
    tableInfo.value.data = [];
  }
}
function changeNum(e, row, str, shouldPayAmount) {
  setTimeout(() => {
    if(row.shouldPayAmount > 0) {
      row.discountsAmount = row.discountsAmount >= row.shouldPayAmount ? shouldPayAmount : row.discountsAmount
    }
    row.payAmount = (row.shouldPayAmount - row.discountsAmount).toFixed(proxy.$store.state.permission.systemConfig.price_precision)
    proxy.$forceUpdate()
  }, 0)
}
function callBackSupplier(row) {
  if (row) {
    formInfo.value.data["supplierName"] = row.supplierName;
    formInfo.value.data["supplierId"] = row.supplierId;
    productInfo.value.query.supplierId = row.supplierId;
    tableInfo.value.data = [];
  }
}
function selectSupplier() {
  // 供应商
  if (!props.orderId) {
    supplierInfo.value.visible = true;
  }
}
function save() {
  proxy.$fn.checkForm(formRefs.value).then(() => {
    if (!tableInfo.value.data.length) {
      proxy.$message({
        duration: 3500,
        type: 'warning',
        message: '产品不能为空',
      })
      return
    }
    let api = undefined;
    if (props.orderId) {
      api = shouldPayOrderUpdate;
    } else {
      api = shouldPayOrderSubmit;
    }
    let params = {
      ...formInfo.value.data,
      details: tableInfo.value.data
    }

    api(params).then((res) => {
      if (res && res.success) {
        proxy.$emit("returnModify");
        showDialog.value = false;
      }
    });
  });
}

function removeProduct(selectRow = undefined) {
  console.log(selectRow)
  if (selectRow && (selectRow.createTime || selectRow.id)) {
    tableInfo.value.data = tableInfo.value.data.filter(
      (row) => row !== selectRow
    );
  } else {
    proxy
      .$confirm("删除后将改变数据,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        tableInfo.value.data = tableInfo.value.data.filter(
          (row) => !tableInfo.value.selections.includes(row)
        );
      });
  }
}
function handleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      tableInfo.value.selections = data;
      break;
  }
}

function addProduct() {
  productInfo.value.query.supplierId = formInfo.value.data.supplierId;
  productInfo.value.visible = true;
  let idNotIn = []
  tableInfo.value.data.map(item => {
    item.extDetails.map(i => {
      idNotIn.push(i.receiptOrderDetailId)
    })
  })
  productInfo.value.query.idNotIn = idNotIn.toString()
}
function selectProduct(rows) {
  tableInfo.value.data = tableInfo.value.data.concat(rows)
}

function getMain() {
  shouldPayOrderDetailAll({orderId: props.orderId}).then((res) => {
    if (res && res.success) {
      tableInfo.value.data = res.data;
     
    }
  });
  getShouldPayOrderDetails(props.orderId).then((res) => {
    if (res && res.success) {
      formInfo.value.data = res.data;
     
    }
  });
}

</script>
